package event

import (
	"fleetmanager/api/errors"
	"fleetmanager/api/params"
	"fleetmanager/api/response"
	"fleetmanager/api/service/base"
	"fleetmanager/api/service/constants"
	"fleetmanager/client"
	"fleetmanager/db/dao"
	"fmt"

	"github.com/beego/beego/v2/server/web"
)

type EventController struct {
	web.Controller
}

func (c *EventController) List() {
	u, err := dao.GetUserResConfByOriProjectId(c.Ctx.Input.Param(params.ProjectId))
	if err != nil {
		response.ServiceError(c.Ctx, errors.NewError(errors.DBError))
		return
	}
	url := fmt.Sprintf(constants.AASSCreateOrListEventUrlPattern, u.OriProjectId)
	code, rsp, e := base.RequestForward(c.Ctx, client.ServiceNameAASS, u.Region, url)
	if e != nil {
		response.ServiceError(c.Ctx, errors.NewError(errors.ServerInternalError))
		return
	}
	response.TransPort(c.Ctx, code, rsp)
}

func (c *EventController) ShowOrDelete() {
	u, err := dao.GetUserResConfByOriProjectId(c.Ctx.Input.Param(params.ProjectId))
	if err != nil {
		response.ServiceError(c.Ctx, errors.NewError(errors.DBError))
		return
	}
	eventId := c.Ctx.Input.Param(params.EventId)
	url := fmt.Sprintf(constants.AASSShowEventUrlPattern, u.OriProjectId, eventId)
	code, rsp, e := base.RequestForward(c.Ctx, client.ServiceNameAASS, u.Region, url)
	if e != nil {
		response.ServiceError(c.Ctx, errors.NewError(errors.ServerInternalError))
		return
	}
	response.TransPort(c.Ctx, code, rsp)
}

func (c *EventController) Topic() {
	u, err := dao.GetUserResConfByOriProjectId(c.Ctx.Input.Param(params.ProjectId))
	if err != nil {
		response.ServiceError(c.Ctx, errors.NewError(errors.DBError))
		return
	}
	url := fmt.Sprintf(constants.AASSTopicEventUrlPattern, u.OriProjectId)
	code, rsp, e := base.RequestForward(c.Ctx, client.ServiceNameAASS, u.Region, url)
	if e != nil {
		response.ServiceError(c.Ctx, errors.NewError(errors.ServerInternalError))
		return
	}
	response.TransPort(c.Ctx, code, rsp)
}

func (c *EventController) AddOrCancelSubscription() {
	u, err := dao.GetUserResConfByOriProjectId(c.Ctx.Input.Param(params.ProjectId))
	if err != nil {
		response.ServiceError(c.Ctx, errors.NewError(errors.DBError))
		return
	}
	topicUrn := c.Ctx.Input.Param(params.TopicUrn)
	subscriptionUrn := c.Ctx.Input.Param(params.SubscriptionUrn)
	if (topicUrn == "" && subscriptionUrn == "") || (topicUrn != "" && subscriptionUrn != "") {
		response.ParamsError(c.Ctx, errors.NewError(errors.InvalidParameterValue))
		return
	}
	url := fmt.Sprintf(constants.AASSTopicSubcriptionUrlPattern, u.OriProjectId, topicUrn+subscriptionUrn)
	code, rsp, e := base.RequestForward(c.Ctx, client.ServiceNameAASS, u.Region, url)
	if e != nil {
		response.ServiceError(c.Ctx, errors.NewError(errors.ServerInternalError))
		return
	}
	response.TransPort(c.Ctx, code, rsp)
}
